//
//  LoginVC.m
//  Project
//
//  Created by 冯东辉 on 2018/9/17.
//  Copyright © 2018年 FengDongHui. All rights reserved.
//

#import "LoginVC.h"
#import "UITextField+Placeholder.h"
#import "BaseTextField.h"
#import <SMS_SDK/SMSSDK.h>

@interface LoginVC () <UITextFieldDelegate>

@property (nonatomic, strong) BaseTextField *phone_tf;

@property (nonatomic, strong) BaseTextField *code_tf;

@property (nonatomic, strong) UIButton *codeBtn;
@property (nonatomic, strong) UILabel *codeLabel;

// 定时器
@property (nonatomic, strong) dispatch_source_t timer;

@property (nonatomic, assign) NSInteger second;

@end

@implementation LoginVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self creatSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
}

/**
 * 加载视图
 */
- (void)creatSubViews {
    
    self.view.backgroundColor = UICOLOR_HEX(0xffffffff);
  
    UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake((GET_SCREEN_WIDTH()-79)/2.0f, (GET_SCREEN_HEIGHT()/2.0f-41-78)/2.0f, 79, 78)];
    logo.image = [UIImage imageNamed:@"logo"];
    [self.view addSubview:logo];
    
    UILabel *logoNote = [[UILabel alloc] initWithFrame:CGRectMake(0, logo.bottom+20, GET_SCREEN_WIDTH(), 20)];
    logoNote.text = @"湖南移动质量掌上通";
    logoNote.textColor = UICOLOR_HEX(0xff1587cd);
    logoNote.font = [UIFont systemFontOfSize:16];
    logoNote.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:logoNote];
    
    CGFloat normalH = 40;
    
    if (GET_SCREEN_HEIGHT() >= 667) {
        
        normalH = 50;
    }
    
    /**
     * 用户名 密码 输入框
     */
    UIView *baseV = [[UIView alloc] initWithFrame:CGRectMake(12, GET_SCREEN_HEIGHT()/2.0f-normalH-1, GET_SCREEN_WIDTH()-24, normalH*2+1)];
    baseV.layer.cornerRadius = 5;
    baseV.layer.borderWidth = 1.0f;
    baseV.layer.borderColor = UICOLOR_HEX(0xffd6d6d6).CGColor;
    [self.view addSubview:baseV];
    
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, normalH, baseV.width, 1)];
    lineV.backgroundColor = UICOLOR_HEX(0xffd6d6d6);
    [baseV addSubview:lineV];
    
    // 用户名
    UIImageView *nameIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, normalH)];
    nameIcon.image = [UIImage imageNamed:@"login_phoneNum"];
    nameIcon.contentMode = UIViewContentModeCenter;
    [baseV addSubview:nameIcon];
    
    _phone_tf = [[BaseTextField alloc] initWithFrame:CGRectMake(nameIcon.right, 0, baseV.width-nameIcon.right, normalH)];
    _phone_tf.delegate = self;
    _phone_tf.placeholder = @"请输入手机号";
    [_phone_tf setPlaceHolderColor:UICOLOR_HEX(0xff999999)];
    _phone_tf.textColor = UICOLOR_HEX(0xff999999);
    _phone_tf.font = [UIFont systemFontOfSize:15];
    _phone_tf.returnKeyType = UIReturnKeyNext;
    _phone_tf.keyboardType = UIKeyboardTypeNumberPad;
    [baseV addSubview:_phone_tf];
    
    NSString *phoneNum = [[NSUserDefaults standardUserDefaults] objectForKey:USER_PHONE_NUM];
    
    if (![ProjectTools isValiString:phoneNum]) {
        _phone_tf.text = phoneNum;
    }
    
    // 验证码
    UIImageView *codeIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, lineV.bottom, nameIcon.width, nameIcon.height)];
    codeIcon.image = [UIImage imageNamed:@"login_code"];
    codeIcon.contentMode = UIViewContentModeCenter;
    [baseV addSubview:codeIcon];
    
    _code_tf = [[BaseTextField alloc] initWithFrame:CGRectMake(_phone_tf.left, codeIcon.top, _phone_tf.width-86-8, _phone_tf.height)];
    _code_tf.delegate = self;
    _code_tf.placeholder = @"请输入验证码";
    [_code_tf setPlaceHolderColor:UICOLOR_HEX(0xff999999)];
    _code_tf.textColor = UICOLOR_HEX(0xff999999);
    _code_tf.font = [UIFont systemFontOfSize:15];
    _code_tf.keyboardType = UIKeyboardTypeNumberPad;
    _code_tf.returnKeyType = UIReturnKeyDone;
    [baseV addSubview:_code_tf];
    
    // 获取验证码按钮
    _codeBtn = [[UIButton alloc] initWithFrame:CGRectMake(_code_tf.right, _code_tf.top+6, 86, _code_tf.height-12)];
    [_codeBtn.layer addSublayer:[ProjectTools setJianBianWithBenginColor:UICOLOR_HEX(0xfffc4a32) endColor:UICOLOR_HEX(0xfffbc042) frame:_codeBtn.bounds cornerRadius:2]];
    [_codeBtn addTarget:self action:@selector(sendMessageCode:) forControlEvents:UIControlEventTouchUpInside];
    [baseV addSubview:_codeBtn];
    
    _codeLabel = [[UILabel alloc] initWithFrame:_codeBtn.bounds];
    _codeLabel.text = @"获取验证码";
    _codeLabel.textColor = UICOLOR_HEX(0xffffffff);
    _codeLabel.font = [UIFont systemFontOfSize:14];
    _codeLabel.textAlignment = NSTextAlignmentCenter;
    [_codeBtn addSubview:_codeLabel];
    
    // 登录按钮
    UIButton *loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(baseV.left, baseV.bottom+50, baseV.width, normalH+4)];
    [loginBtn.layer addSublayer:[ProjectTools setJianBianWithBenginColor:UICOLOR_HEX(0xff169bfa) endColor:UICOLOR_HEX(0xff9977e3) frame:loginBtn.bounds cornerRadius:5]];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:UICOLOR_HEX(0xffffffff) forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(verificationCode) forControlEvents:UIControlEventTouchUpInside];
//    [loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
    // 版权由中国移动所有
    UILabel *showL = [[UILabel alloc] initWithFrame:CGRectMake(0, GET_SCREEN_HEIGHT()-22-20, GET_SCREEN_WIDTH(), 20)];
    showL.text = @"版权由中国移动所有";
    showL.textColor = UICOLOR_HEX(0xff666666);
    showL.font = [UIFont systemFontOfSize:12];
    showL.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:showL];
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if ([textField isEqual:_phone_tf]) {
        
        _code_tf.text = @"";
        
        // 限制手机号11位数
        if ([textField.text length] == 11 && ![string isEqualToString:@""]) {
            
            return NO;
        }
        
    }else {
        
        // 限制验证码6位数
        if ([textField.text length] == 6 && ![string isEqualToString:@""]) {
            
            return NO;
        }
    }
    
    return YES;
}

/**
 * 发送短信验证码
 */
- (void)sendMessageCode:(UIButton *)btn {
    
    if (![ProjectTools isMobileNumber:_phone_tf.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"手机号码不合法"];
        [SVProgressHUD dismissWithDelay:1.5f];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"发送验证码中..."];
    
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_phone_tf.text zone:@"86"  result:^(NSError *error) {
        
        if (!error) {
            
            [SVProgressHUD showSuccessWithStatus:@"验证码发送成功"];
            [SVProgressHUD dismissWithDelay:1.5f];
            
            [self addTimer];
            
        }else {
            
            NSString *errorMsg = [NSString stringWithFormat:@"%@", error.userInfo[@"description"]];
            
            if ([ProjectTools isValiString:errorMsg]) {
                errorMsg = @"验证码发送失败";
            }
            
            [SVProgressHUD showErrorWithStatus:errorMsg];
            [SVProgressHUD dismissWithDelay:1.5f];
        }
    }];
}

/**
 * 定时器
 */
- (void)addTimer {
    
    
    if (self.timer) {
        dispatch_cancel(self.timer);
        self.timer = nil;
    }
    
    _second = 60;
    
    _codeLabel.text = [NSString stringWithFormat:@"倒计时：%02lds", _second];
    _codeBtn.userInteractionEnabled = NO;
    
    dispatch_queue_t queue = dispatch_get_main_queue();
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    uint64_t interval = (uint64_t)(1.0 * NSEC_PER_SEC);
    dispatch_source_set_timer(self.timer, start, interval, 0);
    dispatch_source_set_event_handler(self.timer, ^{
        
        self.second = self.second-1;
        
        if (self.second == 0) {
            
            self.codeBtn.userInteractionEnabled = YES;
            
            self.codeLabel.text = @"获取验证码";
            
            dispatch_cancel(self.timer);
            self.timer = nil;
            
        }else {
            
            self.codeLabel.text = [NSString stringWithFormat:@"倒计时：%02lds", self.second];
        }
    });
    dispatch_resume(self.timer);
}


/**
 * 验证验证码
 */
- (void)verificationCode {
    
    if (![ProjectTools isMobileNumber:_phone_tf.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"手机号码不合法"];
        [SVProgressHUD dismissWithDelay:1.5f];
        return;
    }
    
    if (!_code_tf.text || [_code_tf.text length] < 6) {
        
        [SVProgressHUD showErrorWithStatus:@"验证码不合法"];
        [SVProgressHUD dismissWithDelay:1.5f];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"验证中..."];
    
    [SMSSDK commitVerificationCode:_code_tf.text phoneNumber:_phone_tf.text zone:@"86" result:^(NSError *error) {
        
        if (!error) {
            
            [self login];
            
        }else {
            
            NSString *errorMsg = [NSString stringWithFormat:@"%@", error.userInfo[@"description"]];
            
            if ([ProjectTools isValiString:errorMsg]) {
                errorMsg = @"验证码验证失败";
            }
            
            [SVProgressHUD showErrorWithStatus:errorMsg];
            [SVProgressHUD dismissWithDelay:1.5f];
        }
    }];
}

/**
 * 登录
 */
- (void)login {
    
    [SVProgressHUD showWithStatus:@"登录中..."];
    
    [[ProjectApi instance] loginWithUserId:_phone_tf.text callBack:^(NetModel *object) {
        
        if (object.isSuccessed) {
            
            NSDictionary *json_dic = [object.service firstObject];
            
            [self loginSuccessedHandle:json_dic];
            
        }else {
            
            switch (object.statusCode) {
                case 2:
                    [SVProgressHUD showErrorWithStatus:@"用户信息错误"];
                    [SVProgressHUD dismissWithDelay:1.5f];
                    break;
                case 3:
                    [SVProgressHUD showErrorWithStatus:@"无此用户信息"];
                    [SVProgressHUD dismissWithDelay:1.5f];
                    break;
                default:
                    [SVProgressHUD showErrorWithStatus:@"登录失败"];
                    [SVProgressHUD dismissWithDelay:1.5f];
                    break;
            }
        }
    }];
}

/**
 * 登录成功回调
 */
- (void)loginSuccessedHandle:(NSDictionary *)json_dic {
    
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:IS_CHANGE_USER];
    [[NSUserDefaults standardUserDefaults] setObject:_phone_tf.text forKey:USER_PHONE_NUM];
    [[NSUserDefaults standardUserDefaults] setObject:json_dic forKey:USER_INFO_CITY];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if ([_delegate respondsToSelector:@selector(LoginSuccessCallBack)]) {
        
        [_delegate LoginSuccessCallBack];
    }
}

@end
